﻿//////////////////////////////////////////////////////////////////////////////
//
// Copyright © 1998-2024 Glodon Company Limited.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the “Software”),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////
#include "DBUtils.h"
#include "IDocument.h"
#include "BodiesPositionTypes.h"
#include "AlgorithmPositionJudge.h"
#include "IGraphicsBRepBody.h"
#include <atlhandler.h>
#include "GraphicsNodeUtils.h"
#include "IGraphicsElementShape.h"
#include "EnableCompileWarning_The_LAST_IncludeInCpp.h" 

using namespace Sample;
using namespace gcmp;

std::vector<OwnerPtr<IGraphicsBRepBody>> DBUtils::GetGRepBodies(const gcmp::IDocument * pDoc, const gcmp::IGraphicsElementShape * pGRep)
{
    std::vector<OwnerPtr<IGraphicsBRepBody>> res;
    std::vector<const IGraphicsBRepBody*> gbodies;
    std::vector<Matrix4d> transforms;
    std::vector<std::vector<const IGraphicsNode*>> paths;
    GraphicsNodeUtils::CollectBRepBodies(pDoc, pGRep, &gbodies, &transforms, &paths);

    FOR_EACH_INDEX(index, gbodies)
    {
        OwnerPtr<IGraphicsBRepBody> opGBody = TransferOwnershipCast<IGraphicsBRepBody>(gbodies[index]->Clone());
        bool transformCode = opGBody->Transform(transforms[index]);
        if (transformCode)
        {
            res.push_back(TransferOwnership(opGBody));
        }
    }

    return res;
}

BodiesPositionTypes DBUtils::Intersect(const IGraphicsBRepBody* pFirstBody, const IGraphicsBRepBody *pSecondBody)
{
    DBG_WARN_AND_RETURN_UNLESS(pFirstBody, BodiesPositionTypes::Unknown, L"pFirstBody无效指针", L"GDMP", L"2023-09-30");
    DBG_WARN_AND_RETURN_UNLESS(pSecondBody, BodiesPositionTypes::Unknown, L"pSecondBody无效指针", L"GDMP", L"2023-09-30");

    const IBody* pFirstGmIBody = pFirstBody->GetGeometry();
    const IBody* pSecondGmIBody = pSecondBody->GetGeometry();

    DBG_WARN_AND_RETURN_UNLESS(pFirstGmIBody, BodiesPositionTypes::Separation, L"pFirstGmIBody无效指针", L"GDMP", L"2023-09-30");
    DBG_WARN_AND_RETURN_UNLESS(pSecondGmIBody, BodiesPositionTypes::Separation, L"pSecondGmIBody无效指针", L"GDMP", L"2023-09-30");

    return AlgorithmPositionJudge::GetPosition(pFirstGmIBody, pSecondGmIBody);
}

BodiesPositionTypes DBUtils::Intersect(const gcmp::IDocument* pDoc, const gcmp::IGraphicsElementShape*pFirstGRep, const gcmp::IGraphicsElementShape *pSecondGRep, bool useBox)
{
    DBG_WARN_AND_RETURN_UNLESS(pDoc, BodiesPositionTypes::Separation, L"pDoc无效指针", L"GDMP", L"2023-09-30");
    DBG_WARN_AND_RETURN_UNLESS(pFirstGRep, BodiesPositionTypes::Separation, L"pFirstGRep无效指针", L"GDMP", L"2023-09-30");
    DBG_WARN_AND_RETURN_UNLESS(pSecondGRep, BodiesPositionTypes::Separation, L"pSecondGRep无效指针", L"GDMP", L"2023-09-30");
    BodiesPositionTypes res = BodiesPositionTypes::Unknown;
    if (useBox)
    {
        gcmp::Box3d firstBox = pFirstGRep->GetBox();
        gcmp::Box3d secondBox = pSecondGRep->GetBox();
        if (!firstBox.IsIntersect(secondBox))
        {
            return BodiesPositionTypes::Separation;
        }
    }

    std::vector<OwnerPtr<IGraphicsBRepBody>> opFirstGRepBodies = GraphicsNodeUtils::GetGraphicsBRepBodies(pDoc, pFirstGRep);
    std::vector<OwnerPtr<IGraphicsBRepBody>> opSecondGRepBodies = DBUtils::GetGRepBodies(pDoc, pSecondGRep);
    if (opFirstGRepBodies.size() == 0 || opSecondGRepBodies.size() == 0)
        return BodiesPositionTypes::Unknown;

    std::vector<BodiesPositionTypes> bodysPositionTypes;
    FOR_EACH(firstGRepBody, opFirstGRepBodies)
    {
        FOR_EACH(secondGRepBody, opSecondGRepBodies)
        {
            if (Intersect(firstGRepBody.get(), secondGRepBody.get()) == BodiesPositionTypes::Intersect) // 有一个相交直接返回
                return BodiesPositionTypes::Intersect;
            else if (!firstGRepBody || !secondGRepBody)
                bodysPositionTypes.push_back(BodiesPositionTypes::Unknown);
            else
                bodysPositionTypes.push_back(Intersect(firstGRepBody.get(), secondGRepBody.get()));
        }
    }

    std::sort(bodysPositionTypes.begin(), bodysPositionTypes.end());
    if (*bodysPositionTypes.cbegin() == BodiesPositionTypes::Unknown)
        res = BodiesPositionTypes::Unknown;
    else if (*bodysPositionTypes.cbegin() == BodiesPositionTypes::Tangent)
        res = BodiesPositionTypes::Tangent;
    else
        res = BodiesPositionTypes::Separation;

    return res;
}

gcmp::OwnerPtr<gcmp::IGraphicsBRepBody> DBUtils::GetGRepBody(const gcmp::IDocument* pDoc, const gcmp::IGraphicsElementShape* pGRep)
{
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pDoc, L"pDoc无效指针", L"GDMP", L"2023-09-30");
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pGRep, L"pGRep无效指针", L"GDMP", L"2023-09-30");
    std::vector<const IGraphicsBRepBody*> gbodies;
    std::vector<Matrix4d> transforms;
    std::vector<std::vector<const IGraphicsNode*>> paths;
    GraphicsNodeUtils::CollectBRepBodies(pDoc, pGRep, &gbodies, &transforms, &paths);

    //找出实体Body，默认墙只有一个实体，排除Shell Body，比如墙的中心面，族中作为项目参照的参照平面等
    int solidBodyIndex = -1;
    FOR_EACH_INDEX(gbodyIndex, gbodies)
    {
        if (!gbodies[gbodyIndex]->IsShell())
        {
            solidBodyIndex = gbodyIndex;
            break;
        }
    }

    if (solidBodyIndex == -1)
        return nullptr;

    OwnerPtr<IGraphicsBRepBody> opGBody = TransferOwnershipCast<IGraphicsBRepBody>(gbodies[solidBodyIndex]->Clone());
    if (opGBody->Transform(transforms[solidBodyIndex]))
    {
        return opGBody;
    }

    return nullptr;
}

bool DBUtils::IsIntersect(const gcmp::IDocument* pDoc, const IGraphicsElementShape*pFirstGRep, const IGraphicsElementShape *pSecondGRep)
{
    BodiesPositionTypes posType = DBUtils::Intersect(pDoc, pFirstGRep, pSecondGRep, true);
    if (posType == BodiesPositionTypes::Intersect)
    {
        return true;
    }

    return false;
}
